// 蛇的模型类
import { DIRECTIONS, GRID_SIZE } from '../constants/gameConstants'

export class Snake {
  constructor() {
    this.segments = []
    this.direction = DIRECTIONS.RIGHT
    this.init()
  }

  init() {
    // 初始化蛇的位置
    this.segments = [
      { x: 3, y: 1 },
      { x: 2, y: 1 },
      { x: 1, y: 1 }
    ]
  }

  move() {
    const head = { ...this.segments[0] }
    
    switch (this.direction) {
      case DIRECTIONS.UP:
        head.y--
        break
      case DIRECTIONS.DOWN:
        head.y++
        break
      case DIRECTIONS.LEFT:
        head.x--
        break
      case DIRECTIONS.RIGHT:
        head.x++
        break
    }

    this.segments.unshift(head)
    this.segments.pop()
  }

  grow() {
    const tail = this.segments[this.segments.length - 1]
    this.segments.push({ ...tail })
  }

  setDirection(direction) {
    // 防止180度转向
    if (
      (this.direction === DIRECTIONS.UP && direction === DIRECTIONS.DOWN) ||
      (this.direction === DIRECTIONS.DOWN && direction === DIRECTIONS.UP) ||
      (this.direction === DIRECTIONS.LEFT && direction === DIRECTIONS.RIGHT) ||
      (this.direction === DIRECTIONS.RIGHT && direction === DIRECTIONS.LEFT)
    ) {
      return
    }
    this.direction = direction
  }

  checkCollision() {
    const head = this.segments[0]
    
    // 检查是否撞墙
    if (
      head.x < 0 ||
      head.x >= GRID_SIZE ||
      head.y < 0 ||
      head.y >= GRID_SIZE
    ) {
      return true
    }

    // 检查是否撞到自己
    for (let i = 1; i < this.segments.length; i++) {
      if (head.x === this.segments[i].x && head.y === this.segments[i].y) {
        return true
      }
    }

    return false
  }
}
